import React, { useEffect, useRef, useState } from 'react';
import { connect } from 'react-redux';
import { View, Image, Input } from '@tarojs/components';
import { AtFloatLayout } from 'taro-ui';
import utils from '@/utils/index';
import pBack from '@/images/common/leftGary.svg';
import 'taro-ui/dist/style/components/float-layout.scss';
import './index.scss';

const CodeVerify = ({
  dispatch,
  isOpened,
  handleClose,
  sendCodeResult = false,
  checkCodeResult = {},
  handleDigitWalletPay,
}) => {
  const [codeArr, setCodeArr] = useState(new Array());
  const [isFocus, setIsFocus] = useState(false);
  let firstOpen = useRef(true);
  let codeValue = useRef('');

  const [getCodeText, setGetCodeText] = useState('发送验证码');
  const cutDownTime = useRef(60); //60s
  const [lock, setLock] = useState(true);
  const mobile = utils.getUserMobile() || '';

  useEffect(() => {
    if (isOpened) {
      setIsFocus(true);
    }
    if (isOpened && firstOpen.current) {
      firstOpen.current = false;
      sendCodeByDigitWallet();
    }
  }, [isOpened]);

  const sendCodeByDigitWallet = () => {
    dispatch({
      type: 'otherApi/sendCodeByDigitWallet',
      payload: { templateCode: 'SMS_212487164' },
    });
  };

  const handleReSend = () => {
    if (lock) {
      return;
    }
    if (getCodeText != '重新发送') {
      return;
    }
    sendCodeByDigitWallet();
  };

  useEffect(() => {
    if (sendCodeResult) {
      setLock(true);
      setIsFocus(true);
      let timer = setInterval(function () {
        cutDownTime.current--;
        if (cutDownTime.current <= 0) {
          clearInterval(timer);
          setGetCodeText('重新发送');
          cutDownTime.current = 60;
          setLock(false);
          return;
        }
        setGetCodeText(`${cutDownTime.current}秒后重新发送`);
      }, 1000);
      dispatch({ type: 'otherApi/setSendCodeResult', payload: false });
    }
  }, [sendCodeResult]);

  const handleCodeInput = (e) => {
    codeValue.current = e.target.value;
    let arr = [...codeValue.current];
    setCodeArr(arr);
  };

  const checkCode = () => {
    if (codeValue.current.length != 6) {
      return;
    }
    dispatch({ type: 'otherApi/checkCodeByDigitWallet', payload: { code: codeValue.current } });
  };

  useEffect(() => {
    if (codeValue.current.length == 6 && checkCodeResult.result === true) {
      handleDigitWalletPay();
    } else if (codeValue.current.length == 6 && checkCodeResult.result === false) {
      codeValue.current = '';
      setCodeArr([...codeValue.current]);
    }
  }, [checkCodeResult]);

  return (
    <AtFloatLayout isOpened={isOpened} onClose={handleClose} className="codeVerify">
      <View className="content">
        <View className="theIcon ncenter">
          <Image className="backIcon" src={pBack} onClick={handleClose} />
        </View>
        <View className="ncenter header">身份验证</View>
        <View className="inputArea">
          <View className="title">请输入短信验证码</View>
          <View className="codeArea" onClick={() => setIsFocus(true)}>
            {isOpened && (
              <Input
                className="codeInput"
                type="number"
                maxlength="6"
                value={codeValue.current}
                focus={isFocus}
                autoFocus
                onInput={handleCodeInput}
              />
            )}
            <View className="code ncenter">{codeArr[0] || ''}</View>
            <View className="code ncenter">{codeArr[1] || ''}</View>
            <View className="code ncenter">{codeArr[2] || ''}</View>
            <View className="code ncenter">{codeArr[3] || ''}</View>
            <View className="code ncenter">{codeArr[4] || ''}</View>
            <View className="code ncenter">{codeArr[5] || ''}</View>
          </View>
          <View className="line">
            <View className={['send', lock == false && 'btn'].join(' ')} onClick={handleReSend}>
              {getCodeText}
            </View>
          </View>
        </View>
        <View className="txt ncenter">已发送至手机号{mobile}</View>
        <View className="bottom ncenter">
          <View
            className={['ncenter btn', codeValue.current.length == 6 && 'active'].join(' ')}
            onClick={checkCode}
          >
            确认支付
          </View>
        </View>
      </View>
    </AtFloatLayout>
  );
};
export default connect(({ otherApi }) => ({
  sendCodeResult: otherApi.sendCodeResult,
  checkCodeResult: otherApi.checkCodeResult,
}))(CodeVerify);
